package xyz.keyon.servlet;

import xyz.keyon.bean.User;
import xyz.keyon.service.IUserService;
import xyz.keyon.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取响应头信息
        String name = request.getParameter("uname");
        String password = request.getParameter("upwd");
        //调用业务逻辑层
        IUserService service = new UserServiceImpl();
        User user = service.login(name, password);
        //处理返回结果
        if(user != null) {
            System.out.println("登录成功");
            System.out.println("username:" + user.getUsername());
            System.out.println("password:" + user.getPassword());
            request.getSession().setAttribute("username", user.getUsername());
            request.getSession().setMaxInactiveInterval(30); //Session存活时间30s
            //页面跳转（重定向）
            response.sendRedirect("QueryAllStudentsByPageServlet");
        } else {
            request.setAttribute("status","failed");
            System.out.println("登录失败");
            //页面跳转（请求转发）
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
